package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.PurchaseOrder;
import cn.wolfcode.crm.domain.PurchaseOrderItem;
import cn.wolfcode.crm.domain.Stock;
import cn.wolfcode.crm.mapper.PurchaseOrderItemMapper;
import cn.wolfcode.crm.mapper.PurchaseOrderMapper;
import cn.wolfcode.crm.mapper.StockMapper;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPurchaseOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class PurchaseOrderServiceImpl implements IPurchaseOrderService {

    @Autowired
    private PurchaseOrderMapper mapper;
    @Autowired
    private PurchaseOrderItemMapper itemMapper;
    @Autowired
    private StockMapper stockMapper;

    public void insert(PurchaseOrder entity) {
        entity.setInputTime(new Date());//设置当前保存时间为下单时间
        entity.setInputUser(new Employee());//设置当前登录账户为输入人
        BigDecimal totalNumber = BigDecimal.ZERO;
        BigDecimal totalAmount = BigDecimal.ZERO;//初始化
        //遍历页面传过来的items信息
        List<PurchaseOrderItem> purchaseOrderItems = entity.getPurchaseOrderItems();
        //保存订单总数和单总额
        for (PurchaseOrderItem item : purchaseOrderItems) {
            totalNumber = totalNumber.add(item.getNumber());
            totalAmount = totalAmount.add(item.getNumber().multiply(item.getCostPrice()));
        }
        entity.setTotalNumber(totalNumber);
        entity.setTotalAmount(totalAmount.setScale(BigDecimal.ROUND_HALF_UP,2));
        mapper.insert(entity);

        //保存订单明细
        for (PurchaseOrderItem item : purchaseOrderItems) {
            item.setPurchaseOrderId(entity.getId());//保存订单id
            item.setAmount(item.getCostPrice().multiply(item.getNumber()));
            itemMapper.insert(item);
        }
    }

    public void delete(Long id) {
        //先删除订单名细
        itemMapper.deleteByOrderId(id);
        mapper.deleteByPrimaryKey(id);
    }

    public void update(PurchaseOrder entity) {
        BigDecimal totalNumber = BigDecimal.ZERO;
        BigDecimal totalAmount = BigDecimal.ZERO;//初始化
        //遍历页面传过来的items信息
        List<PurchaseOrderItem> purchaseOrderItems = entity.getPurchaseOrderItems();
        //删除旧明细再保存新的明细
        itemMapper.deleteByOrderId(entity.getId());
        //更新订单总数和单总额
        for (PurchaseOrderItem item : purchaseOrderItems) {
            totalNumber = totalNumber.add(item.getNumber());
            totalAmount = totalAmount.add(item.getNumber().multiply(item.getCostPrice()));
            //更新订单明细
            item.setPurchaseOrderId(entity.getId());//保存订单id
            item.setAmount(item.getCostPrice().multiply(item.getNumber()));
            itemMapper.updateByPrimaryKey(item);
        }
        entity.setTotalNumber(totalNumber);
        entity.setTotalAmount(totalAmount.setScale(BigDecimal.ROUND_HALF_UP,2));
        mapper.updateByPrimaryKey(entity);

    }

    public PurchaseOrder get(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<PurchaseOrder> list() {
        return mapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int total = mapper.queryForCount(qo);
        List<PurchaseOrder> rows = mapper.queryForList(qo);
        return new PageResult(total,rows);
    }


    //审核订单  审核后改变stock的库存数量
    public void audit(Long id) {
        PurchaseOrder purchaseOrder = mapper.selectByPrimaryKey(id);//找到需要审核的订单
        //先判断为未审核再执行操作
        if (purchaseOrder.getState() == PurchaseOrder.STATE_UNAUDIT){
            purchaseOrder.setAuditor(new Employee());//设置当前登录的账号为审核账号
            purchaseOrder.setAuditTime(new Date());//设置当前时间为审核时间
            purchaseOrder.setState(PurchaseOrder.STATE_AUDIT);//设置状态为已审核

            //入库保存/更新
            List<PurchaseOrderItem> items = purchaseOrder.getPurchaseOrderItems();
            for (PurchaseOrderItem item : items) {
                Stock stock = new Stock();//创建库存对象
                //先判断商品是否存在(根据商品的sn和name判断)
                if (stockMapper.selectByNameAndSn(item.getProduct().getName(),item.getProduct().getSn()) != null){
                    //获取到库存中的商品信息
                    stock =stockMapper.selectByNameAndSn(item.getProduct().getName(),item.getProduct().getSn());
                    //更新库存信息
                    stock.setTotalNumber(stock.getTotalNumber().add(item.getNumber()));
                    stock.setTotalAmount(stock.getTotalAmount().add(item.getNumber().
                            multiply(item.getCostPrice().setScale(BigDecimal.ROUND_HALF_UP,2))));

                    stock.setCostPrice((item.getCostPrice().add(stock.getCostPrice())).
                            divide(new BigDecimal(2),BigDecimal.ROUND_HALF_UP,2));
                    stockMapper.updateByPrimaryKey(stock);
                }else{
                    stock.setTotalNumber(item.getNumber());
                    stock.setTotalAmount(item.getNumber().multiply(item.getCostPrice()).
                            setScale(BigDecimal.ROUND_HALF_UP,2));
                    stock.setInputTime(new Date());//设置当前时间为添加入库时间
                    stock.setInputUser(new Employee());//设置当前登录用户为审核人
                    stock.setCostPrice(item.getCostPrice());
                    stock.setProductName(item.getProduct().getName());
                    stock.setProductSn(item.getProduct().getSn());
                    stock.setProductSize(item.getProduct().getSize());
                    stockMapper.insert(stock);
                }
            }
        }
    }
}
